﻿using UnityEditor;
using UnityEngine;

namespace EditorExtension
{
    [InitializeOnLoad] // 初始时调用一次
    public static class HierarchyExample
    {
        private static bool mCustomHierarchyEnabled = false;
        private const string PATH = "EditorExtensions/02_IMGUI/03_Enable Custom Hierarchy";

        static HierarchyExample()
        {
            Menu.SetChecked(PATH, mCustomHierarchyEnabled);
        }
        
        [MenuItem(PATH)]
        static void EnableCustomHierarchy()
        {
            mCustomHierarchyEnabled = !mCustomHierarchyEnabled;
            Menu.SetChecked(PATH, mCustomHierarchyEnabled);
            
            if (mCustomHierarchyEnabled)
            {
                RegisterHierarchy();
            }
            else
            {
                UnRegisterHierarchy();
            }
            
            // 立刻重绘
            EditorApplication.RepaintHierarchyWindow();
        }

        static void RegisterHierarchy()
        {
            // 绘制 Hierarchy
            EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyGUI;
            
            // 监听 Hierarchy 变化
            EditorApplication.hierarchyChanged += OnHierarchyChanged;
        }

        private static void OnHierarchyChanged()
        {
            Debug.Log("Hierarchy Changed");
        }

        private static void OnHierarchyGUI(int instanceID, Rect selectionRect)
        {
            var obj = EditorUtility.InstanceIDToObject(instanceID) as GameObject;
            
            // 绘制标签
            Rect tagLabelRect = selectionRect;
            tagLabelRect.x += 100;
            GUI.Label(tagLabelRect, obj?.tag);
            
            // 绘制层级
            Rect layerLabelRect = selectionRect;
            layerLabelRect.x += 200;
            GUI.Label(layerLabelRect, LayerMask.LayerToName(obj ? obj.layer : 0));
        }

        static void UnRegisterHierarchy()
        {
            EditorApplication.hierarchyWindowItemOnGUI -= OnHierarchyGUI;
            EditorApplication.hierarchyChanged -= OnHierarchyChanged;
        }
    }
}